package com.duqc.rocketmq;

import com.duqc.constants.OperateType;
import com.duqc.web.dto.CanalDTO;
import com.duqc.web.dto.TbCommodityInfoDTO;
import com.duqc.redis.RedisUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @ClassName MQDataHandle
 * @Description TODO
 * @Author duqc
 * @Date 2021/4/14
 **/
@Slf4j
@Component
@RequiredArgsConstructor
public class MQDataHandle {

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

        private final RedisUtil redisUtils;

    /**
     * 消息处理
     *
     * @param body
     * @return
     */
    public boolean dataHandle(String body) {
        try {
            CanalDTO canalDTO = OBJECT_MAPPER.readValue(body, CanalDTO.class);
            //获取是否是DDL语句
            boolean isDdl = canalDTO.getIsDdl();
            //获取类型
            String type = canalDTO.getType();
            if (!isDdl) {
                List<TbCommodityInfoDTO> data = canalDTO.getData();
                if (CollectionUtils.isEmpty(data)) {
                    return false;
                }
                //新增,修改
                if (OperateType.INSERT.name().equals(type) || OperateType.UPDATE.name().equals(type)) {
                    data.forEach(info -> {
                        Long id = info.getId();
                        redisUtils.setString(String.valueOf(id), info, 600L);
                    });
                }
                //删除
                if (OperateType.DELETE.name().equals(type)) {
                    data.forEach(info -> {
                        Long id = info.getId();
                        redisUtils.deleteKey(String.valueOf(id));
                    });
                }
                return true;
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return false;
    }
}
